<!-- components/inventory/ProductImportExport.vue -->
<template>
  <el-drawer
    v-model="visible"
    :title="mode === 'import' ? '导入产品' : '导出产品'"
    direction="rtl"
    size="500px"
    @close="handleClose"
  >
    <div v-if="mode === 'import'">
      <div class="template-download">
        <el-button 
          type="primary" 
          link
          @click="downloadTemplate"
          :loading="downloadingTemplate"
        >
          <el-icon><Download /></el-icon>
          下载导入模板
        </el-button>
        <p class="template-tip">请先下载模板，按照模板格式填写产品信息</p>
      </div>
      
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        drag
        :action="uploadUrl"
        :headers="uploadHeaders"
        :data="uploadData"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :auto-upload="false"
      >
        <el-icon class="el-icon--upload">
          <UploadFilled />
        </el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传.xlsx或.csv格式的文件，文件大小不超过10MB
          </div>
        </template>
      </el-upload>
    </div>
    
    <div v-else>
      <el-form :model="exportParams" label-width="100px">
        <el-form-item label="导出格式">
          <el-radio-group v-model="exportParams.format">
            <el-radio value="xlsx">Excel (.xlsx)</el-radio>
            <el-radio value="csv">CSV (.csv)</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="筛选条件">
          <el-checkbox v-model="exportParams.includeFilters">
            包含当前筛选条件
          </el-checkbox>
        </el-form-item>
        
        <el-form-item label="导出字段">
          <el-checkbox 
            v-model="exportParams.selectAll" 
            @change="handleSelectAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group 
            v-model="exportParams.selectedFields" 
            class="field-checkbox-group"
          >
            <el-checkbox 
              v-for="field in exportableFields" 
              :key="field.value"
              :value="field.value"
            >
              {{ field.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button 
        type="primary" 
        @click="handleConfirm"
        :loading="submitting"
      >
        {{ mode === 'import' ? '开始导入' : '开始导出' }}
      </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled, Download } from '@element-plus/icons-vue'
import * as inventoryAPI from '@/api/inventory'

const props = defineProps<{
  modelValue: boolean
  mode: 'import' | 'export'
  filterParams: any
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

const visible = ref(false)
const submitting = ref(false)
const downloadingTemplate = ref(false)
const uploadRef = ref()

// 导出参数
const exportParams = ref({
  format: 'xlsx',
  includeFilters: true,
  selectAll: true,
  selectedFields: [
    'sku', 'name', 'specification', 'unit', 'categoryId', 'categoryName',
    'brand', 'stock', 'minStock', 'salePrice', 'costPrice', 'status'
  ]
})

// 可导出字段
const exportableFields = [
  { value: 'sku', label: 'SKU' },
  { value: 'name', label: '产品名称' },
  { value: 'specification', label: '规格' },
  { value: 'unit', label: '单位' },
  { value: 'categoryId', label: '类目ID' },
  { value: 'categoryName', label: '类目名称' },
  { value: 'brand', label: '品牌' },
  { value: 'stock', label: '当前库存' },
  { value: 'minStock', label: '安全库存' },
  { value: 'salePrice', label: '售价' },
  { value: 'costPrice', label: '成本价' },
  { value: 'status', label: '状态' }
]

// 上传配置
const uploadUrl = '/inventory/products/import'
const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem('token')}`
}
const uploadData = {}

// 监听modelValue变化
watch(() => props.modelValue, (newValue) => {
  visible.value = newValue
})

// 监听visible变化
watch(visible, (newValue) => {
  emit('update:modelValue', newValue)
})

const handleClose = () => {
  visible.value = false
}

const handleSelectAllChange = (checked: boolean) => {
  if (checked) {
    exportParams.value.selectedFields = exportableFields.map(field => field.value)
  } else {
    exportParams.value.selectedFields = []
  }
}

const handleUploadSuccess = (response: any) => {
  ElMessage.success('产品导入成功')
  emit('success')
  handleClose()
}

const handleUploadError = (error: any) => {
  ElMessage.error('产品导入失败: ' + error.message)
}

const handleConfirm = async () => {
  if (props.mode === 'import') {
    // 触发上传
    uploadRef.value?.submit()
  } else {
    // 导出产品
    await exportProducts()
  }
}

const exportProducts = async () => {
  submitting.value = true
  try {
    let params: any = {}
    
    // 如果包含筛选条件
    if (exportParams.value.includeFilters) {
      params = { ...props.filterParams }
    }
    
    // 添加导出参数
    params.format = exportParams.value.format
    params.fields = exportParams.value.selectedFields.join(',')
    
    const blob = await inventoryAPI.exportProducts(params)
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `products_${new Date().toISOString().slice(0, 10)}.${exportParams.value.format}`
    link.click()
    
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('产品导出成功')
    emit('success')
    handleClose()
  } catch (error) {
    ElMessage.error('产品导出失败: ' + (error as Error).message)
  } finally {
    submitting.value = false
  }
}

const downloadTemplate = async () => {
  downloadingTemplate.value = true
  try {
    const blob = await inventoryAPI.getImportTemplate()
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = 'product_import_template.xlsx'
    link.click()
    
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('模板下载成功')
  } catch (error) {
    ElMessage.error('模板下载失败: ' + (error as Error).message)
  } finally {
    downloadingTemplate.value = false
  }
}
</script>

<style scoped>
.field-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 12px;
}

.field-checkbox-group .el-checkbox {
  width: 30%;
  margin-right: 0;
}

.template-download {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  text-align: center;
  background-color: #f5f7fa;
}

.template-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}
</style>